package com.zhucai.credit.service.impl.loop;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.zhucai.common.locks.DistributedLockFactory;
import com.zhucai.common.locks.DistributedReentrantLock;
import com.zhucai.credit.bank.bean.BankTransfer;
import com.zhucai.credit.bank.service.IFactoringService;
import com.zhucai.credit.bank.service.impl.CcbEPointServiceImpl;
import com.zhucai.credit.bean.CreditRecord;
import com.zhucai.credit.common.CommonEnums.CrAprovalStatus;
import com.zhucai.credit.common.CommonEnums.CrProdType;
import com.zhucai.credit.common.CommonEnums.CrProdstatus;
import com.zhucai.credit.common.CommonEnums.CreditStatus;
import com.zhucai.credit.common.CommonEnums.CreditUnusualStatus;
import com.zhucai.credit.common.HelpConstant;
import com.zhucai.credit.model.CreditApplicationEntity;
import com.zhucai.credit.model.CreditProductEntity;
import com.zhucai.credit.model.CreditRecordEntrity;
import com.zhucai.credit.model.PaymentOrderItemEntity;
import com.zhucai.credit.repository.CreditApplicationRepository;
import com.zhucai.credit.repository.CreditProductRepository;
import com.zhucai.credit.repository.CreditRecordRepository;
import com.zhucai.credit.repository.PaymentOrderItemRepository;
import com.zhucai.credit.repository.PaymentOrderRepository;

/**
 * 金融订单定时任务
 * @author hsg
 */
@Service("orderLoopService")
public class OrderLoopService {
	private static final Logger logger = LoggerFactory.getLogger(OrderLoopService.class);
	@Autowired
	private DistributedLockFactory distributedLockFactory;
	@Autowired
	private CreditRecordRepository creditRecordRepository;
	@Autowired
	private PaymentOrderRepository paymentOrderRepository;
	@Autowired
	private PaymentOrderItemRepository paymentOrderItemRepository;
	@Autowired
	private CcbEPointServiceImpl CCBSericeImpl;
	@Autowired
	private Map<String, IFactoringService> bankLinkageService;
	@Autowired
	private CreditProductRepository creditProductRepository;
	@Autowired
	private CreditApplicationRepository creditApplicationRepository;
	/**
	 * 一分钟执行一次
	 */
//	@Scheduled(fixedRate = 60000)
	public void orderLoop() {
		logger.trace("loop：orderLoop start");
		DistributedReentrantLock lock = distributedLockFactory.buildLock("orderLoop");
		if (lock.tryLock(1000)) {
			try {
				try {
					changeOrderInfo();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} finally {
				lock.unlock();
				logger.trace("loop：orderLoop complete");
			}
		} else {
			logger.trace("loop：orderLoop is running in other jvm ,this thread end");
		}
	}
	/**
	 * 定时更新金融企业名称
	 * @author shoffice
	 * @version 2018年9月10日
	 */
//	@Scheduled(cron = "0 0/15 * * * ?" )//每15分钟更新
	public void changeEntNameTask() {
		logger.trace("loop：changeEntNameLoop start");
		DistributedReentrantLock lock = distributedLockFactory.buildLock("changeEntNameLoop");
		if (lock.tryLock(1000)) {
			try {
				try {
					changeEntName();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} finally {
				lock.unlock();
				logger.trace("loop：changeEntNameLoop complete");
			}
		} else {
			logger.trace("loop：changeEntNameLoop is running in other jvm ,this thread end");
		}
	}
	/**
	 * 工商银行自动续时间
	 * @version 2018年10月10日
	 */
	@Scheduled(cron = "0 0/1 * * * ?" )//每15分钟更新
//	@Scheduled(cron = "0 0 12 * * ?" )//每天中午十二点触发 
	public void ICBCContinuedTimeTask() {
		logger.trace("ICBCContinuedTime start");
		DistributedReentrantLock lock = distributedLockFactory.buildLock("ICBCContinuedTimeLoop");
		if (lock.tryLock(1000)) {
			try {
				try {
					ICBCContinuedTime();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} finally {
				lock.unlock();
				logger.trace("loop：ICBCContinuedTimeLoop complete");
			}
		} else {
			logger.trace("loop：ICBCContinuedTimeLoop is running in other jvm ,this thread end");
		}
	}
	private void ICBCContinuedTime() {
		//查询正常的供应商工行资质记录
		List<CreditApplicationEntity> rsList = creditApplicationRepository.findBankOverdue(CrProdType.ICBC_R_E_J.toString());
		
		if(CollectionUtils.isNotEmpty(rsList)){
			for (CreditApplicationEntity creditApplicationEntity : rsList) {
				//过期时间当做自动续约的开始时间
				Date crProdStartTime = creditApplicationEntity.getCrProdEndTime();
				//结束时间自动加一年
				Date crProdEndTime = DateUtils.addYears(crProdStartTime, 1);
				CreditApplicationEntity cae = new CreditApplicationEntity();
				BeanUtils.copyProperties(creditApplicationEntity, cae);
				SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
				String appNum = "ICBC" + sf.format(new Date());
				cae.setAppNum(appNum);
				cae.setTid(null);
				cae.setCrApplyTime(new Date());
				cae.setCrProdStartTime(crProdStartTime);
				cae.setCrProdEndTime(crProdEndTime);
				CreditApplicationEntity save = creditApplicationRepository.save(cae);
				if(save != null && save.getTid().compareTo(creditApplicationEntity.getTid()) != 0){
					creditApplicationRepository.updateStatus(creditApplicationEntity.getTid(), CrAprovalStatus.OVER.toString(), CrProdstatus.EXPIRED.toString());
				}
			}
			//新增自动续约一年的记录
			
		}
		
	}
	private void changeEntName() {
		creditApplicationRepository.updatePurEntName();
		creditApplicationRepository.updateSupEntName();
	}
	/**
	 * 更新融资业务状态
	 */
	public void changeOrderInfo(){
		
		
 		List<PaymentOrderItemEntity> orderList = paymentOrderItemRepository.findPayOrderItemForInfo(HelpConstant.Status.delete, "02");
		if(CollectionUtils.isEmpty(orderList)){
			return;
		}
		for (PaymentOrderItemEntity paymentOrderItemEntity : orderList) {
			String orderNo = paymentOrderItemEntity.getOrderNo();
			changeOrderByRcordNo(orderNo);
		}
		
	}
	public void changeOrderByRcordNo(String recordNo){
		//状态集合
		List<String> statusList = new ArrayList<String>();
		statusList.add(CreditStatus.WAIT_PAY.toString());//待支付状态
		statusList.add(CreditStatus.SUMBIT_TO_BANK.toString());//待提交银行
		//根据融资编号查询融资信息
		List<CreditRecordEntrity> rsList = creditRecordRepository.findByStatusListAndRecordNo(HelpConstant.Status.delete,recordNo,statusList);
		if(CollectionUtils.isEmpty(rsList)){
			logger.error("### orderId={},查询融资记录失败",recordNo);
			return;
		}
		CreditRecordEntrity cre = rsList.get(0);
		CreditRecord cr = new CreditRecord();
		BeanUtils.copyProperties(cre, cr);
		//调用银行接口、
		BankTransfer bankTransfer = new BankTransfer();
		BeanUtils.copyProperties(cre, bankTransfer);
		CreditProductEntity cpe = creditProductRepository.findByTidAndStatusNot(cre.getCrProdId(), HelpConstant.Status.delete);
		IFactoringService iFactoringService = bankLinkageService.get(cpe.getCrProdType());
		CreditRecord credit = iFactoringService.apply(bankTransfer);
		if("OK".equals(credit.getReturnStatus())){
			cre.setCreditStatus(CreditStatus.SUBSTITUTE_CONTRACT.toString());
			cre.setRejectReason(null);
			cre.setCreditUnusualStatus(CreditUnusualStatus.NORMAL.toString());
			creditRecordRepository.updateUnusualStatus(HelpConstant.Status.delete,cre.getTid(),CreditUnusualStatus.NORMAL.toString(),null,CreditStatus.SUBSTITUTE_CONTRACT.toString());
			logger.info("更新融资记录成功，data={},调用银行接口成功，ccbdata={}",cre,cr);
		}else{
			logger.info("6W5574提交银行失败时，data={},调用银行行接口失败，error={}",cre,credit.getReturnMessage());
			//更新融资异常状态为提交银行网络异常
//			credit.setRejectReason("连接超时,请稍后再试!");
			Integer coo = creditRecordRepository.updateUnusualStatus(HelpConstant.Status.delete,cre.getTid(),CreditUnusualStatus.NETWORK_ERROR.toString(),credit.getReturnMessage(),CreditStatus.SUMBIT_TO_BANK.toString());
			if(coo != 1){
				logger.info("6W5574提交银行失败时更新融资异常状态失败，recordNo={}",cre.getRecordNo());
			}
		}
	}
}
